<template>
    <div>
        <quill-editor
            ref="QuillEditor"
            v-model="content"
            :options="editorOption"
            class="quill-s"
        >
        </quill-editor>
    </div>
</template>
<script>
import {ossUpload, selectFile} from "@/utils/file";
import {uuid} from "@/utils";
import {Quill} from "vue-quill-editor"

const toolbarOptions = [
    ["bold", "italic", "underline", "strike"],
    [{list: "ordered"}],
    [{script: "sub"}, {script: "super"}],
    [{color: []}, {background: []}],
    [{align: []}],
    ["image"],
    ["voice"]
]

export default {
    components: {},
    props: {
        inputValue: {
            type: [Number,String , Object],
            default: ""
        }
    },
    data() {
        return {
            content: "",
            fullscreenLoading: false,
            editorOption: {
                modules: {
                    toolbar: {
                        container: toolbarOptions,  // 工具栏
                        handlers: {
                            "image": (value) => {
                                if (value) {
                                    // 在这里编写图片按钮点击操作
                                    this.initQuillImage()
                                } else {
                                    this.quill.format("image", false)
                                }
                            },
                            "voice": (value) => {     //添加工具方法，即点击时模仿点击上传组件的按钮
                                if (value) {
                                    // 在这里编写音频按钮点击操作
                                    this.initQuillVoice()
                                } else {
                                    this.quill.format("voice", false)
                                }
                            }
                        }
                    }
                },
                placeholder: "请输入...",
                initVoiceButton: function () {
                    //初始化"voice"按钮样式
                    //"ql-" 是插件自动加的前缀
                    const voiceButton = document.querySelector(".ql-voice");
                    // 添加样式，使用fontawesome初始化图标的样式
                    voiceButton.classList.add("el-icon-headset");
                    // 也可以直接手写样式，如：
                    /* voiceButton.style.cssText = "width:80px; border:1px solid #ccc; border-radius:5px;";
                    voiceButton.innerText="上传音频";*/
                }
            },
            uploadVisible: false,
            baseUrl: "https://vipcdn.langrundata.com/",
            contentVl: ""
        }
    },
    watch: {
        content(vl) {
            this.$emit("update:inputValue", vl);
        },
        inputValue(vl) {
            this.content = vl;
        }
    },
    created() {
        this.content = this.inputValue;
    },
    mounted() {
        let quill = this.$refs.QuillEditor.quill;
        // 监听粘贴的图片上传
        quill.root.addEventListener(
            "paste",
            (evt) => {
                if (
                    evt.clipboardData &&
                    evt.clipboardData.files &&
                    evt.clipboardData.files.length
                ) {
                    let files = [];
                    for (
                        let i = 0;
                        i < evt.clipboardData.files.length;
                        i++
                    ) {
                        files.push(evt.clipboardData.files[i]);
                    }
                    files = files.filter((file) =>
                        file.type.match(/^image\/(gif|jpe?g|a?png|bmp)/i)
                    );
                    if (files.length > 0) {
                        evt.preventDefault();
                        files = files.filter((v) => {
                            if (v.size > 10 * 1024 * 1024) {
                                this.$notify({
                                    title: "警告",
                                    message: "粘贴图片大于10M已被忽略",
                                    type: "warning",
                                });
                                return false;
                            }
                            return true;
                        });
                        if (files.length > 0) {
                            const loading = this.$loading({
                                lock: true,
                                text: "图片上传中",
                                spinner: "el-icon-loading",
                                background: "rgba(0, 0, 0, 0.5)",
                            });
                            Promise.all(
                                files.map(async (file) => {
                                    const fileName =
                                        uuid(32, 16) +
                                        "." +
                                        file.name.split(".")[1];
                                    return ossUpload(
                                        "cdn",
                                        fileName,
                                        file
                                    ).catch((e) => {
                                        this.$notify({
                                            title: "警告",
                                            message:
                                                "图片上传失败，请重新上传",
                                            type: "error",
                                        });
                                    });
                                })
                            )
                                .then((res) => {
                                    for (let url of res) {
                                        if (!url) continue;
                                        const range = quill.getSelection();
                                        quill.insertEmbed(
                                            range.index,
                                            "image",
                                            this.baseUrl + url
                                        );
                                    }
                                })
                                .catch((e) => {
                                    console.error(e);
                                })
                                .finally(() => loading.close());
                        }
                    }
                }
            },
            false
        );
        //初始化音频图标，这样才能显示
        this.editorOption.initVoiceButton();
    },
    methods: {
        beforeUpload(file) {
            // file.type好像只能返回图片的格式，其他的将会是 ""， 所以需要自己获取后缀名判断文件格式
            let pointIndex = file.name.lastIndexOf(".");
            let fileType = file.name.substring(pointIndex + 1);   //获取到文件后缀名
            // if (fileType !== 'mp3' && fileType !== 'ogg' && fileType !== 'wav') {
            if (fileType !== "mp3" && fileType !== "ogg") {
                this.$message.error("你选择的文件不是音频哦，仅支持mp3和ogg格式")
                return false
            }
        },
        uploadIng() {        //上传时显示loading
            this.fullscreenLoading = true
        },
        // 上传图片
        initQuillImage() {
            let quill = this.$refs.QuillEditor.quill
            const toolbar = quill.getModule("toolbar");
            toolbar.addHandler("image", async (v1, v2, v3) => {
                if (v1) {
                    const range = quill.getSelection();
                    if (range) {
                        const index = range.index;
                        selectFile(
                            (file) => {
                                const loading = this.$loading({
                                    lock: true,
                                    text: "图片上传中",
                                    spinner: "el-icon-loading",
                                    background: "rgba(0, 0, 0, 0.5)",
                                });
                                ossUpload("cdn", null, file)
                                    .then((res) => {
                                        quill.insertEmbed(
                                            index,
                                            "image",
                                            this.baseUrl + res
                                        );
                                        setTimeout(() => {
                                            loading.close();
                                        }, 500);
                                    })
                                    .catch((e) => {
                                        // console.log("eee:", e);
                                        this.$message.error("图片上传失败");
                                        loading.close();
                                    });
                            },
                            (dom) => {
                                dom.accept =
                                    "image/jpg,image/png,image/jpeg,image/gif,";
                            }
                        );
                    }
                }
            });
        },
        // 上传音频
        initQuillVoice() {
            let quill = this.$refs.QuillEditor.quill;
            const _this = this;
            const toolbar = quill.getModule("toolbar");
            toolbar.addHandler("voice", async (v1, v2, v3) => {
                if (v1) {
                    const range = quill.getSelection();
                    if (range) {
                        const index = range.index;
                        selectFile(
                            (file) => {
                                let testmsg = file.name.substring(file.name.lastIndexOf(".") + 1)
                                const extension = testmsg === "mp3"
                                if (!extension) {
                                    return this.$message({
                                        message: "上传音频只能是mp3格式！",
                                        type: "error"
                                    })
                                }
                                const loading = this.$loading({
                                    lock: true,
                                    text: "音频上传中",
                                    spinner: "el-icon-loading",
                                    background: "rgba(0, 0, 0, 0.5)",
                                });
                                ossUpload("cdn", null, file)
                                    .then((res) => {
                                        // 获取光标所在位置
                                        let length = quill.getSelection().index;
                                        let BlockEmbed = Quill.import("blots/block/embed");

                                        class AudioBlot extends BlockEmbed {
                                            static create(value) {
                                                let node = super.create();
                                                //设置audio的src属性
                                                node.setAttribute("src", _this.baseUrl + res);
                                                //设置audio的controls，否则他将不会显示
                                                node.setAttribute("controls", true);
                                                //设置audio的下载功能为不能下载
                                                node.setAttribute("controlsList", "nodownload");
                                                //设置一个id
                                                node.setAttribute("id", "voice");
                                                return node;
                                            }
                                        }

                                        AudioBlot.blotName = "audio";
                                        //自定义的标签为audio
                                        AudioBlot.tagName = "audio";
                                        Quill.register(AudioBlot);
                                        // insertEmbed(index: Number(插入的位置), type: String(标签类型), value: any(参数，将传入到create的方法中去), source: String = 'api')
                                        quill.insertEmbed(length, "audio", {url: this.baseUrl + res}, "api");
                                        //光标位置向后移动一位
                                        quill.setSelection(length + 1);
                                        setTimeout(() => {
                                            loading.close();
                                        }, 500);
                                    })
                                    .catch((e) => {
                                        console.log("eee:", e);
                                        this.$message.error("音频上传失败");
                                        loading.close();
                                    });
                            },
                            (dom) => {
                                dom.accept = "voice/mp3";
                            }
                        );
                    }
                }
            });
        }
    }
}
</script>
<style scoped>
.quill-s {
    margin-bottom: 10px;
    background: #fff;
}

.ql-voice {
    background: #0a76a4;
    width: 12px;
    height: 12px;

}
</style>

